package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.article.IArticleClient;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.file.MinIoTemplate;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.schedule.dto.Task;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.OcrUtil;
import com.heima.utils.ProtostuffUtil;
import com.heima.utils.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.AutoScanService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.TesseractException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author itheima
 * @since 2022-07-13
 */
@Service
@Slf4j
public class AutoScanServiceImpl implements AutoScanService {

    @Autowired
    private WmNewsService wmNewsService;

    @Autowired
    private MinIoTemplate minIoTemplate;

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;


    @Override
    public void autoScanWmNews(Integer newsId) throws Exception {
        if (newsId == null) {
            log.warn("文章审核的入参为空");
            return;
        }

        // 1. 查询wmNews
        WmNews news = wmNewsService.getById(newsId);
        if (news == null) {
            log.warn("新闻" + newsId + "为空");
            return;
        }

        // 2. 提取文字 String getText(String title, String content)
        String title = news.getTitle();
        String content = news.getContent();
        String text = getText(title, content);

        // 3. 提取图片 List<byte[]> getImage(String images, String content)
        String images = news.getImages();
        List<byte[]> image = getImage(images, content);

        //   通过ocr提取图片文字
        String textFromOcr = ocrCheck(image);
        text = text + "_" + textFromOcr;


        //自管理的敏感词过滤
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(null);
        if (!CollectionUtils.isEmpty(wmSensitives)) {
            // 提取敏感词字段
            List<String> words = wmSensitives.stream().filter(Objects::nonNull).map(WmSensitive::getSensitives).collect(Collectors.toList());

            // 初始化敏感词
            SensitiveWordUtil.initMap(words);

            // 匹配
            Map<String, Integer> sensitivesResult = SensitiveWordUtil.matchWords(text);

            // 如果结果大于0，证明没通过
            if (sensitivesResult.size() > 0) {
                log.warn("敏感词审核未通过");
                updateNews(newsId, 2, "敏感词审核未通过", null);
                return;
            }
        }


        // 4. 审核文字 GreenTextScan
        Map textScan = greenTextScan.greeTextScan(text);
        Boolean suggestion = getSuggestion(textScan, newsId);
        if (!suggestion) {
            log.warn("文字审核失败");
            return;
        }

        // 5. 审核图片 GreenImageScan
        Map imageScan = greenImageScan.imageScan(image);
        Boolean suggestion2 = getSuggestion(imageScan, newsId);
        if (!suggestion2) {
            log.warn("图片审核失败");
            return;
        }

        // 6. 保存文章 调用Article feign接口
        ArticleDto dto = wmNews2ArticleDto(news);
        ResponseResult responseResult = articleClient.saveArticle(dto);
        Integer code = responseResult.getCode();
        if (code != 200) {
            log.warn("保存文章失败");
            return;
        }
        Long articleId = (Long) responseResult.getData();

        // 7. 回写wmNews状态和ArticleId
        updateNews(newsId.intValue(), 9, "通过", articleId);
    }


    /***
     *  OCR提取图片文字
     * @param images
     * @return
     * @throws IOException
     * @throws TesseractException
     */

    private String ocrCheck(List<byte[]> images) throws IOException, TesseractException {
        if (CollectionUtils.isEmpty(images)) {
            return "";
        }
        StringBuilder builder = new StringBuilder();
        for (byte[] image : images) {
            //调用ocr工具类.提取里面的文字内容
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(image);
            BufferedImage read = ImageIO.read(byteArrayInputStream);

            String text = OcrUtil.doOcr(read);

            //将文字内容组合成一个字符串返回
            builder.append("_").append(text);
        }
        return builder.toString();
    }

    /**
     * ArticleDto入参转换
     *
     * @param wmNews wmNews
     * @return ArticleDto
     */
    public ArticleDto wmNews2ArticleDto(WmNews wmNews) {
        if (wmNews == null) {
            return null;
        }

        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews, dto);

        // 处理差异字段
        Integer userId = wmNews.getUserId();
        dto.setAuthorId(userId.longValue());
        WmUser wmUser = wmUserMapper.selectById(userId);
        if (wmUser != null) {
            dto.setAuthorName(wmUser.getName());
        }

        // 获取频道信息
        Integer channelId = wmNews.getChannelId();
        WmChannel wmChannel = wmChannelMapper.selectById(channelId);
        if (wmChannel != null) {
            dto.setChannelName(wmChannel.getName());
        }

        // 布局方式
        dto.setLayout(wmNews.getType());
        dto.setCreatedTime(new Date());

        return dto;
    }

    /**
     * 分析阿里云审核结果
     *
     * @param result result
     * @param newsId newsId
     * @return Boolean
     */
    private Boolean getSuggestion(Map result, Integer newsId) {
        if (!CollectionUtils.isEmpty(result)) {
            Object suggestion = result.get("suggestion");
            if ("block".equals(suggestion)) {
                // 不通过
                updateNews(newsId, 2, "不通过", null);
                return false;
            } else if ("review".equals(suggestion)) {
                // 不确定
                updateNews(newsId, 3, "不确定", null);
                return false;
            }
        }

        return true;
    }

    /**
     * 回写news状态
     *
     * @param newsId    新闻id
     * @param status    状态
     * @param reason    审核结果
     * @param articleId 文章id
     * @return Boolean
     */
    private Boolean updateNews(Integer newsId, Integer status, String reason, Long articleId) {
        WmNews wmNews = new WmNews();
        wmNews.setId(newsId);
        wmNews.setReason(reason);
        wmNews.setStatus(status.shortValue());
        if (articleId != null) {
            wmNews.setArticleId(articleId);
        }

        return wmNewsService.updateById(wmNews);
    }

    /**
     * 提取文字
     *
     * @param title   标题
     * @param content 内容
     * @return String
     */
    private String getText(String title, String content) {
        // 1. 将content转为List<Map>
        List<Map> maps = JSON.parseArray(content, Map.class);
        if (CollectionUtils.isEmpty(maps)) {
            log.warn("content内容为空");
            return title;
        }

        StringBuilder builder = new StringBuilder();

        // 2. 提取content里面的文字部分
        for (Map map : maps) {
            if (CollectionUtils.isEmpty(map)) {
                continue;
            }

            Object type = map.get("type");
            if ("text".equals(type)) {
                String value = (String) map.get("value");
                builder.append(value);
            }
        }

        // 3. 将content的文字和title进行组装
        builder.append("_").append(title);

        // 4. 返回结果
        return builder.toString();
    }

    /**
     * 提取图片
     *
     * @param images  封面图
     * @param content 内容
     * @return List
     */
    private List<byte[]> getImage(String images, String content) {
        List<String> allImageList = new ArrayList<>();

        // 1. 判断images是否为空
        if (StringUtils.isNotEmpty(images)) {
            // 2. 提取images里面的图片链接（,) split()
            String[] split = images.split(",");
            List<String> list = Arrays.asList(split);

            allImageList.addAll(list);
        }

        // 3. 提取content里面的图片
        List<Map> maps = JSON.parseArray(content, Map.class);
        if (!CollectionUtils.isEmpty(maps)) {
            List<String> contentImageList = new ArrayList<>();
            for (Map map : maps) {
                if (CollectionUtils.isEmpty(map)) {
                    continue;
                }

                Object type = map.get("type");
                if ("image".equals(type)) {
                    String value = (String) map.get("value");
                    contentImageList.add(value);
                }
            }

            allImageList.addAll(contentImageList);
        }

        // 4. 把上面两组图片地址 合并在一起
        List<byte[]> result = new ArrayList<>();
        for (String img : allImageList) {
            if (StringUtils.isEmpty(img)) {
                continue;
            }

            // 5. 借助minIO的download将string转为byte[]
            byte[] bytes = minIoTemplate.downLoadFile(img);
            result.add(bytes);
        }

        // 6. 组装byte[]集合，并返回
        return result;
    }

    @Autowired
    private IScheduleClient scheduleClient;

    @Scheduled(fixedRate = 1000)
    public void getTask() {
        ResponseResult poll = scheduleClient.poll();
        if (poll == null || poll.getCode() != 200) {
            log.warn("消费失败");
            return;
        }

        String data = (String) poll.getData();
        if (StringUtils.isEmpty(data)){
            log.warn("没有可消费的任务");
            return;
        }

        Task task = JSON.parseObject(data, Task.class);
        if (task==null){
            log.warn("没有可消费的任务");
            return;
        }
        byte[] parameters = task.getParameters();
        WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);
        if (wmNews==null){
            log.warn("参数缺失");
            return;
        }
        try {
            autoScanWmNews(wmNews.getId().intValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}